<template>
  <div>
    <van-tabs v-model="active">
      <van-tab title="积分充值">
        <form action="/">
          <van-dropdown-menu>
            <van-dropdown-item
              v-model="listQuery.retailer_id"
              :options="retailers"
              @change="onRetailerChange"
            />
            <van-dropdown-item title="时间查询" ref="item1">
              <van-field
                style="padding-left: 23px"
                left-icon="calendar-o"
                clickable
                readonly
                name="calendar"
                :value="recharge_range_date"
                placeholder="点击选择日期"
                @click="showCalendar = true"
                clearable
              />
            </van-dropdown-item>
          </van-dropdown-menu>
        </form>
        <van-calendar
          type="range"
          v-model="showCalendar"
          :min-date="minDate"
          @confirm="onRechargeConfirm"
        />
        <van-cell-group>
          <van-cell title="积分/充值合计" value="">
            <template>
              {{ recordScores.scores }}/ ¥{{ recordScores.cash_fees }}
            </template>
          </van-cell>
        </van-cell-group>
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-cell-group>
            <van-cell
              v-for="item in records"
              :key="item.id"
              :title="item.retailer_name"
              :value="item.score"
              :label="item.pay_time"
            >
              <template
                >{{ item.score }} / {{ item.cash_fee }}
                <van-tag :type="item.status == 1 ? 'success' : 'warning'">{{
                  item.status_name
                }}</van-tag></template
              >
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>
      <van-tab title="赠送积分">
        <form action="/">
          <van-dropdown-menu>
            <van-dropdown-item title="姓名查询" ref="item">
              <van-search
                v-model="bonusQuery.name"
                clearable
                show-action
                placeholder="请输入搜索姓名"
                @search="onBonusSearch"
                @cancel="onBonusCancel"
              />
            </van-dropdown-item>
            <van-dropdown-item title="时间查询" ref="item1">
              <van-field
                style="padding-left: 23px"
                left-icon="calendar-o"
                clickable
                readonly
                name="calendar"
                :value="bonus_range_date"
                placeholder="点击选择日期"
                @click="showBonusCalendar = true"
                clearable
              />
            </van-dropdown-item>
            <van-dropdown-item
              v-model="bonusQuery.retailer_id"
              :options="retailers"
              @change="onItemChange"
            />
          </van-dropdown-menu>
        </form>
        <van-calendar
          type="range"
          v-model="showBonusCalendar"
          :min-date="minDate"
          @confirm="onBonusConfirm"
        />
        <van-cell-group>
          <van-cell title="积分合计" value="">
            <template>
              <van-tag type="success">{{ bonusScores.scores }}</van-tag>
              <span v-if="bonusScores.unused_scores != 0">
                +
                <van-tag type="warning">{{
                  bonusScores.unused_scores
                }}</van-tag></span
              >
            </template>
          </van-cell>
        </van-cell-group>
        <van-list
          v-model="bonusLoading"
          :finished="bonusFinished"
          finished-text="没有更多了"
          @load="onBonusLoad"
        >
          <van-cell-group>
            <van-cell
              is-link
              v-for="item in bonusPoints"
              :key="item.id"
              :title="item.retailer_name"
              :value="item.score"
              :label="item.update_time"
              @click="infoDetail(item)"
            >
              <template>
                <span>{{ item.score }}</span>
                <span v-if="item.unused_score != 0">
                  + <van-tag type="warning">{{ item.unused_score }}</van-tag>
                </span>
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>
      <van-tab title="积分消费">
        <form action="/">
          <van-search
            v-model="consumeQuery.name"
            clearable
            show-action
            placeholder="请输入搜索姓名"
            @search="onConsumeSearch"
            @cancel="onConsumeCancel"
          />
          <van-field
            style="padding-left: 23px"
            left-icon="calendar-o"
            clickable
            readonly
            name="calendar"
            :value="consume_range_date"
            placeholder="点击选择日期"
            @click="showConsumeCalendar = true"
            clearable
          />
        </form>
        <van-calendar
          type="range"
          v-model="showConsumeCalendar"
          :min-date="minDate"
          @confirm="onConsumeConfirm"
        />
        <van-cell-group>
          <van-cell title="消费合计" value="">
            <template>
              <van-tag type="success">{{ consumeScores.scores }}</van-tag>
            </template>
          </van-cell>
        </van-cell-group>
        <van-list
          v-model="consumeLoading"
          :finished="consumeFinished"
          finished-text="没有更多了"
          @load="onConsumeLoad"
        >
          <van-cell-group>
            <van-cell
              is-link
              v-for="item in consumePoints"
              :key="item.id"
              :title="item.name"
              :value="item.score"
              :label="item.update_time"
              @click="infoConsumeDetail(item)"
            >
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>
      <van-tab title="客户生日">
        <form action="/">
          <van-field
            style="padding-left: 23px"
            left-icon="calendar-o"
            clickable
            readonly
            name="calendar"
            :value="birthday"
            placeholder="点击选择日期"
            @click="showBirthCalendar = true"
            clearable
          />
        </form>
        <van-calendar v-model="showBirthCalendar" @confirm="onBirthConfirm" />
        <van-list
          v-model="birthLoading"
          :finished="birthFinished"
          finished-text="没有更多了"
          @load="onBirthLoad"
        >
          <van-cell-group>
            <van-cell
              v-for="item in users"
              :key="item.id"
              :title="item.name"
              :value="item.birthday"
              :label="item.telephone"
            >
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>
    </van-tabs>
    <van-action-sheet
      title="详细情况"
      v-model="actionShow"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
    >
      <van-form>
        <van-field
          v-model="info.order_no"
          name="order_no"
          label="单号"
          placeholder="单号"
        />
        <van-field
          v-model="info.retailer_name"
          name="retailer_name"
          label="商家名称"
          placeholder="商家名称"
        />
        <van-field
          v-model="info.name"
          name="name"
          label="赠送人"
          placeholder="员工姓名"
        />
        <van-field
          v-model="info.customer_name"
          name="customer_name"
          label="客户姓名"
          placeholder="客户姓名"
        />
        <van-field
          v-model="info.score"
          name="score"
          label="赠送积分"
          placeholder="赠送积分"
        />
        <van-field
          v-if="info.unused_score > 0"
          v-model="info.unused_score"
          name="unused_score"
          label="待激活积分"
          placeholder="待激活积分"
        />
        <van-field
          v-model="info.update_time"
          name="update_time"
          label="时间"
          placeholder="时间"
        />
      </van-form>
    </van-action-sheet>
    <van-action-sheet
      title="详细情况"
      v-model="consumeShow"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
    >
      <van-form>
        <van-field
          v-model="info.name"
          name="name"
          label="客户姓名"
          placeholder="客户姓名"
        />
        <van-field
          v-model="info.employee_name"
          name="employee_name"
          label="核销人"
          placeholder="核销人姓名"
        />
        <van-field
          v-model="info.score"
          name="score"
          label="消费积分"
          placeholder="消费积分"
        />
        <van-field
          v-model="info.update_time"
          name="update_time"
          label="时间"
          placeholder="时间"
        />
      </van-form>
    </van-action-sheet>
  </div>
</template>

<script>
import { formatDateTime } from "@/utils/datetime";
import { getStaffUsers } from "@/api/wechat";
import {
  getRechargeRecords,
  getBonusPoints,
  getPointConsumptions,
  getAllRetailers,
  getBonusPointStats,
  getRechargeStats,
  getConsumeStats,
} from "@/api/user";

export default {
  name: "BillList",
  components: {},
  data() {
    return {
      active: 0,
      title: this.$route.meta.title,
      info: {},
      loading: false,
      finished: false,
      records: [],

      bonusLoading: false,
      bonusFinished: false,
      bonusPoints: [],

      consumeLoading: false,
      consumeFinished: false,
      consumePoints: [],

      birthLoading: false,
      birthFinished: false,
      users: [],

      showCalendar: false,
      showBonusCalendar: false,
      showConsumeCalendar: false,
      showBirthCalendar: false,

      search_date: null,
      recharge_range_date: null,
      bonus_range_date: null,
      consume_range_date: null,
      birthday: null,

      retailers: [],

      bonusScores: {},
      recordScores: {},
      consumeScores: {},

      listQuery: {
        page: 1,
        page_size: 5,
        search_date: null,
        retailer_id: 0,
      },

      bonusQuery: {
        page: 1,
        page_size: 10,
        name: "",
        search_date: null,
        retailer_id: 0,
      },

      consumeQuery: {
        page: 1,
        page_size: 10,
        name: "",
        search_date: null,
      },

      birthQuery: {
        page: 1,
        page_size: 10,
        birthday: formatDateTime(new Date(), "YYYY-MM-DD"),
      },

      actionShow: false,
      consumeShow: false,
    };
  },
  computed: {
    minDate() {
      let datetime = new Date();
      datetime = datetime.setFullYear(datetime.getFullYear() - 5);
      return new Date(datetime);
    },
  },
  mounted() {
    this.getRetailers();
  },
  methods: {
    getRetailers() {
      getAllRetailers().then((res) => {
        this.retailers.push({ text: "全部商家", value: 0 });
        const retailers = res.data.map((item) => {
          return { text: item.name, value: item.id };
        });
        this.retailers.push(...retailers);
      });
    },

    getBonusStats() {
      getBonusPointStats(this.bonusQuery).then((res) => {
        this.bonusScores = res.data;
      });
    },

    getRechargeStats() {
      getRechargeStats(this.listQuery).then((res) => {
        this.recordScores = res.data;
      });
    },

    getConsumePointStats() {
      getConsumeStats(this.consumeQuery).then((res) => {
        console.log(res);
        this.consumeScores = res.data;
      });
    },

    ///显示积分详细情况
    onCancel() {
      this.actionShow = false;
      this.consumeShow = false;
      this.info = {};
    },

    infoDetail(data) {
      this.info = data;
      this.actionShow = true;
    },

    infoConsumeDetail(data) {
      this.info = data;
      this.consumeShow = true;
    },

    //充值记录
    onLoad() {
      this.getRechargRecords();
      this.getRechargeStats();
    },

    getRechargRecords() {
      getRechargeRecords(this.listQuery).then((res) => {
        if (res.data.results.length === 0) {
          this.records = []; // 清空数组
          this.finished = true; // 停止加载
        }
        this.listQuery.page = res.data.page;
        this.records.push(...res.data.results);
        this.loading = false;

        if (this.records.length >= res.data.count) {
          this.finished = true; // 结束加载状态
        }
      });
    },

    onRechargeConfirm(date) {
      const [start, end] = date;
      this.showCalendar = false;
      const begin_date = formatDateTime(start, "YYYY-MM-DD");
      const end_date = formatDateTime(end, "YYYY-MM-DD");

      this.recharge_range_date = `${begin_date} / ${end_date}`;
      this.listQuery.search_date = [begin_date, end_date];
      this.listQuery.page = 1;
      this.records = [];
      this.onLoad();
    },

    onRetailerChange() {
      this.listQuery.page = 1;
      this.records = [];
      this.onLoad();
    },

    //赠送积分
    onBonusLoad() {
      this.getBonusPointList();
      this.getBonusStats();
    },

    getBonusPointList() {
      getBonusPoints(this.bonusQuery)
        .then((res) => {
          if (res.data.results.length === 0) {
            this.bonusPoints = []; // 清空数组
            this.bonusFinished = true; // 停止加载
          }
          this.bonusQuery.page = res.data.page;
          this.bonusPoints.push(...res.data.results);
          this.bonusLoading = false;

          if (this.bonusPoints.length >= res.data.count) {
            this.bonusFinished = true; // 结束加载状态
          }
        })
        .catch((error) => {
          this.loading = false;
          this.finished = true;
          if (error.response) {
            this.$notify({
              type: "danger",
              message: "读取积分数据失败" + error,
            });
          }
        });
    },

    onBonusSearch() {
      this.$refs.item.toggle();
      this.bonusPoints = [];
      this.bonusQuery.page = 1;
      this.onBonusLoad();
    },

    onBonusCancel() {
      this.bonusPoints = [];
      this.bonus_range_date = null;
      this.bonusQuery.search_date = null;
      this.bonusQuery.page = 1;
      this.bonusQuery.retailer_id = 0;

      this.onBonusLoad();
    },

    onBonusConfirm(date) {
      const [start, end] = date;
      this.showBonusCalendar = false;
      const begin_date = formatDateTime(start, "YYYY-MM-DD");
      const end_date = formatDateTime(end, "YYYY-MM-DD");

      this.bonus_range_date = `${begin_date} / ${end_date}`;
      this.bonusQuery.search_date = [begin_date, end_date];
      this.bonusQuery.page = 1;
      this.bonusPoints = [];
      this.onBonusLoad();
    },

    onItemChange() {
      this.bonusQuery.page = 1;
      this.bonusPoints = [];
      this.onBonusLoad();
    },

    //消费积分
    onConsumeLoad() {
      this.getConsumePointList();
      this.getConsumePointStats();
    },

    getConsumePointList() {
      getPointConsumptions(this.consumeQuery).then((res) => {
        if (res.data.results.length === 0) {
          this.consumePoints = []; // 清空数组
          this.consumeFinished = true; // 停止加载
        }
        this.consumeQuery.page = res.data.page;
        this.consumePoints.push(...res.data.results);
        this.consumeLoading = false;

        if (this.consumePoints.length >= res.data.count) {
          this.consumeFinished = true; // 结束加载状态
        }
      });
    },

    onConsumeSearch() {
      this.consumePoints = [];
      this.consumeQuery.page = 1;
      this.onConsumeLoad();
    },

    onConsumeCancel() {
      this.consumePoints = [];
      this.consume_range_date = null;
      this.consumeQuery.search_date = null;
      this.consumeQuery.name = "";
      this.consumeQuery.page = 1;

      this.onConsumeLoad();
    },

    onConsumeConfirm(date) {
      const [start, end] = date;
      this.showConsumeCalendar = false;
      const begin_date = formatDateTime(start, "YYYY-MM-DD");
      const end_date = formatDateTime(end, "YYYY-MM-DD");

      this.consume_range_date = `${begin_date} / ${end_date}`;
      this.consumeQuery.search_date = [begin_date, end_date];
      this.consumeQuery.page = 1;
      this.consumePoints = [];
      this.onConsumeLoad();
    },
    //客户生日
    onBirthConfirm(date) {
      this.showBirthCalendar = false;
      this.birthday = formatDateTime(date, "YYYY-MM-DD");

      this.birthQuery.birthday = this.birthday;
      this.birthQuery.page = 1;
      this.users = [];
      this.onBirthLoad();
    },
    onBirthLoad() {
      getStaffUsers(this.birthQuery).then((res) => {
        if (res.data.results.length === 0) {
          this.users = []; // 清空数组
          this.birthFinished = true; // 停止加载
        }
        this.birthQuery.page = res.data.page;
        this.users.push(...res.data.results);
        this.birthLoading = false;

        if (this.users.length >= res.data.count) {
          this.birthFinished = true; // 结束加载状态
        }
      });
    },
  },
};
</script>

<style  scoped>
.van-cell__title {
  flex: 2;
}
</style>